package lms.view;

import lms.entity.Book;
import lms.entity.Borrow;
import lms.entity.Reader;
import lms.service.BorrowService;
import lms.service.OperationService;
import lms.service.impl.BookServiceImpl;
import lms.service.impl.BorrowServiceImpl;
import lms.service.impl.ReaderServiceImpl;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.function.DoubleBinaryOperator;

/**
 * @description: 管理员管理界面
 * @author: Grape_Pip
 * @time: 2021/06/21
 */
public class ManageBorrowView {
    public Scanner scan = new Scanner(System.in);
    public OperationService bookService = new BookServiceImpl();
    public OperationService readerService = new ReaderServiceImpl();
    public BorrowService borrowService = new BorrowServiceImpl();

    public ManageBorrowView() throws ParseException {
        borrowOperation();
    }

    public void borrowOperation() throws ParseException {

        boolean flags;
        borrowManageShow();
        System.out.println("请输入您要选择的操作：");
        String bOption = scan.next();
        switch (bOption) {
            case "1":
                int bid;
                Borrow bo = new Borrow();
//                借阅
                //                验证+输入读者编号
                System.out.println("读者id:");
                int rid;
                do {
                    rid = scan.nextInt();
                    boolean result = readerIdInput(rid);
                    if (result) {
                        flags = false;
                        bo.setBorrowReaderId(rid);
                    } else {
                        flags = true;
                        System.out.println("没有查到读者信息!请重新输入:");
                    }
                } while (flags);


//                验证+输入图书编号
                System.out.println("书id:");
                do {
                    bid = scan.nextInt();
                    boolean result = bookIdInput(bid);
                    if (result) {
                        flags = false;
                        bo.setBorrowISBN(bid);
                    } else {
                        flags = true;
                        System.out.println("没有这本书!请重新输入:");
                    }
                } while (flags);

//                读者借阅书籍重复，则借阅失败！
                Borrow selectedInfo = borrowService.selectedBorrowByBRid(bid, rid);
                if (selectedInfo == null) {
                    Book selectedBook = (Book) bookService.selectedById(bid);
                    boolean flagBorrow;
                    if (selectedBook.getBookStock() <= 0) {
                        System.out.println("此图书暂无库存！");
                    } else {
                        //                输入借阅数量
                        System.out.println("请输入你要借阅的书本数量:");
                        do {
                            int borrowNum = scan.nextInt();
                            //                判断输入的借阅数量<=库存
                            if (0 < borrowNum && borrowNum <= selectedBook.getBookStock()) {
                                bo.setBorrowSum(borrowNum);
//                    借阅日期
                                Date borrowDate = new Date();
                                bo.setBorrowDate(borrowDate);

                                boolean updateBookNum = bookService.updateStocksById(bid, (selectedBook.getBookStock() - borrowNum));
                                boolean insertBorrowRes = borrowService.addedBorrowInfo(bo);

                                if (updateBookNum && insertBorrowRes) {
                                    System.out.println("借阅成功!\n库存已更新!\n");
                                } else {
                                    System.out.println("借阅失败!\n");
                                }
                                flagBorrow = false;
                            } else {
                                System.out.println("没那么多书给你借!\n");
                                System.out.println("你借的 <<" + selectedBook.getBookName() + ">>,剩余数量为: " + selectedBook.getBookStock() + "本!");
                                System.out.println("请重新输入借阅数量:");
                                flagBorrow = true;
                            }
                        } while (flagBorrow);
                    }
                } else {
                    System.out.println("读者正在借阅此书，请先归还后在进行借阅！");
                }

                borrowOperation();
                break;

            case "2":
//                归还
//                输入bid,rid  -Borrow 计算借阅天数>=本读者类型最大借阅天数 =差值;<= 不输入:0 显示罚金:
//                结算后,更新数据 sum\returntime\status\bfine
//                同时更新Book的库存.
                System.out.println("请输入归还的图书ISBN:");
                int bobid = scan.nextInt();
                System.out.println("请输入归还的读者ID:");
                int borid = scan.nextInt();
                Borrow borr = borrowService.selectedBorrowByBRid(bobid, borid);
                if (borr != null) {
                    System.out.println("读者目前借阅此书籍:" + borr.getBorrowSum() + "本");
//                把Date格式的日期转换为毫秒值
                    long borrowTime = borr.getBorrowDate().getTime();
//                获取当前日期，转换为毫秒值
                    long todayTime = System.currentTimeMillis();
//                当前毫秒值减去生日毫秒值
                    long diffTime = todayTime - borrowTime;
//                转换为天数
                    long borrowDay = diffTime / 1000 / 60 / 60 / 24;

//                    读者类型借阅最大天数查询
                    Reader reader = (Reader) readerService.selectedById(borid);
                    int readerLimit = reader.getReaderType().getLimit();
//                    比较

                    System.out.println("读者确认归还么?(y/n)");
                    String inputString = scan.next();
                    switch (inputString) {
                        case "y":
                            if (borrowDay <= readerLimit) {
                                returnAllInfo(bobid, borid, borr, 0.0);
                                break;
                            } else {
//                                有罚金
                                System.out.println("你已逾期:" + (borrowDay - readerLimit) + "天");
                                double bfine = (borrowDay - readerLimit) * 0.88 * borr.getBorrowSum();
                                System.out.println("需要缴纳:" + bfine + "元罚金");
                                System.out.println("读者是否缴纳罚金？(y/n)");
                                String fineInput = scan.next();
                                if (fineInput.equals("y")) {
                                    returnAllInfo(bobid, borid, borr, bfine);
                                    System.out.println("Success!");
                                } else {
                                    System.out.println("归还失败！返回上一级。");
                                    borrowOperation();
                                }
                            }
                        case "n":
                            System.out.println("已返回上一级!");
                            borrowOperation();
                            break;
                        default:
                            System.out.println("输入有误,已返回上一级!");
                            borrowOperation();
                            break;
                    }
                    System.out.println("");
                } else {
                    System.out.println("没有相关借阅记录!");
                }
                borrowOperation();
                break;
            case "3":
//                查询借阅
                List<Borrow> borrowsList = borrowService.selectedAllBorrowInfo();
                System.out.println("| 查询结果为：");
                if (borrowsList != null && !borrowsList.isEmpty()) {
                    for (Borrow borrows : borrowsList) {
                        System.out.println(borrows);
                    }
                } else {
                    System.out.println("无任何借阅记录~~~");
                    System.out.println();
                }
                borrowOperation();
                break;

            case "0":
                new ManageView().mOperation();//上一层
            default:
                System.out.println("无此操作哦~");
                borrowOperation();
                break;
        }

    }


    public void returnAllInfo(int bobid, int borid, Borrow borr, Double bfine) {
        //                        图书更新库存,先查,再更新
        Book bok = (Book) bookService.selectedById(bobid);
//                        新的库存=现有+归还
        int newStocks = bok.getBookStock() + borr.getBorrowSum();
        bok.setBookStock(newStocks);
        boolean updateBookStock = bookService.updatedById(bobid, bok);
//                        直接归还,更新
        borr.setBorrowSum(0);
        borr.setReturnDate(new Date());
        borr.setBoStatus(1);
        borr.setBorrowFine(bfine);
        boolean updateBorr = borrowService.updateReturnBook(bobid, borid, borr);
        if (updateBookStock && updateBorr) {
            System.out.println("归还成功!");
        } else {
            System.out.println("归还失败!");
        }

    }

    /**
     * @return void
     * @Description //TODO 借阅功能展示
     * @Param []
     **/
    public void borrowManageShow() {
        System.out.println("^========图书馆管理系统 v2.0========^");
        System.out.println("<========     借阅管理     ========>");

        System.out.println("|---------- 1、借阅图书 -----------|");
        System.out.println("|---------- 2、归还图书 -----------|");
        System.out.println("|---------- 3、查看借阅信息 --------|");
        System.out.println("|---------- 0、返回上一层  ---------|");
        System.out.println();
    }

    public boolean bookIdInput(int bid) {
        boolean flag = false;

        Book selectedBook = (Book) bookService.selectedById(bid);
        if (selectedBook != null) {
            flag = true;
            System.out.println("图书名称:" + selectedBook.getBookName() + ", 图书库存:" + selectedBook.getBookStock() + "\n");
        } else {
            flag = false;
        }
        return flag;
    }

    public boolean readerIdInput(int rid) {
        boolean flag = false;

        Reader selectedReader = (Reader) readerService.selectedById(rid);
        if (selectedReader != null) {
            flag = true;
            System.out.println("读者姓名:" + selectedReader.getReaderName() + ", 读者Tel:" + selectedReader.getReaderTel() + "\n");
        } else {
            flag = false;
        }
        return flag;
    }
}
